;(function () {

	Array.prototype.removeRepeatBuildingAndFLoor = function () {
	  var res = [this[0]];
	  for (var i = 1; i < this.length; i++) {
	    var repeat = false;
	    for (var j = 0; j < res.length; j++) {
	      if (this[i].buildingName == res[j].buildingName && this[i].floorNum == res[j].floorNum) {
	        repeat = true;
	      }
	    }
	    if (!repeat) {
	      res.push(this[i]);
	    }
	  }
	  return res;
	};

	new Vue({
		el: '#contract-flow-change',
		data () {
			return {
				tabData: [
					{name: '合同变更信息', disabled: true, privilege: null},
					// {name: '账单变更信息', disabled: true, privilege: null},
					{name: '流程信息', disabled: true, privilege: null},
				],
				contract:'',
				rent:[],
				billParams: {history_contract_id: ''},
				selectTabData: '合同变更信息',
				data: {commissionRules: [], alterInfoVO: {},expenses:[]},
				resourceMes:{
				  st: [],
				  ot: []
				},   // 资源信息
				building:[],  // 楼宇数据
				totalArea:0,
				unit:[], // 单元
				st: [], // 车位
				wp: [], // 工位
				pExpense: [],
				oExpense: [],
				tExpense: [],
				billChangeData: {conflictBills: [], confilctSettleUpBill: {billExpense: []}},
				contract: {commissionRules: []},
				contractId: 3487,
				versionDisplay: false,
				groupLogs: [],
				params: hlUrlUtil.$query(),
				unitId: null, // 单元id
				unitDetailsFlag: false,
				contractFile: [],
				progress: '',
				bpm:{},  // 工作流程信息
				bpmList:[], // 工作流程列表
				flowNode:[], // 流程节点
				cutChangeFlowFlag: false,
				freeDate: [],

				publicLogsTypes: ['text', 'value', 'change', 'delete'],
				publicGroup: ['Y', 'N'],
				publicFlag: ['Y', 'N'],
				permissions: JSON.parse(window.localStorage.getItem('permissions')),
				freeDate: [],
				payData: [],
				oldPayData: [],

				newData: [],
				subtotalTableWidth: 170,
				payPlanTableWidth: 140,
				subtotalArr: {},
				oObj: {name: '一次性费用', expense: 0},
				//总计应付
				total: 0,
				types: ['R', 'P', 'CM'],
				oTypes: ['O', 'D', 'T'],
				intentionAmount: 0,
				tmpData: [],
				
				ops1: {
				  bar: {
				    background: '#000',
						onlyShowBarOnScroll: false,
						keepShow: false,
						hoverStyle: false,
						size: '10px',
						opacity: 0.3
				  },
					scrollPanel: {
						scrollingX: true,
						scrollingY: false
					}
				},
				alertFile:[],

				monthRentPriceAlert:'',
				dayRentPriceAlert:'',
				breakPriceFlag:'',
				contractBdate:'',
				contractEdate:'',
				moneyCha:0,
				conflictBills:'',
				effectiveRD:'',
				effectiveRM:''
			}
		},
		computed: {
			dototal: function () {
				var result = 0;
        this.data.expenses.map(function (item) {
          if (item.expenseType == 'D') {
            result++
          }
				})
				return result
      },
			yaTotal(){
				console.log(this.data.expenses)
				let num = 0
        this.data.expenses.map(item =>{
          if(item.expenseType == 'D'){
            num = num + Number(item.amount)
          }
        })
        return num.toFixed(2)
      }
    },
		filters: {
		  formatDate: function(time) {
		    if (time === undefined)return '--'
		    return hlDateUtil.formatUTCDate(time, 'yyyy-MM-dd')
		  },
			formAlterType (item) {
				let res = '';
				switch (item){
					case 'ALL':
						res = '基本信息变更;条款变更'
						break;
					case 'YB':
						res = '基本信息变更'
						break;
					case 'CW':
						res = '条款变更'
						break;
					default:
						res = '--'
						break;
				}
				return res
			},
		  formatDetailDate:function (time) {
		    if (time === undefined) return '--'
		    return hlDateUtil.formatUTCDate(time)
		  },
		  formatUndefined: function(item) {
		    if (!item)return '--'
		    return item
		  },
		  formatIndustry: function(item) {
		    return hlCodeConvert.industryType(item)
		  },
		  formatZlfType:function(item){
		    return hlCodeConvert.contractZlfType(item)
		  },
		  formatContractType:function(item){
		    return hlCodeConvert.contractType(item)
		  },
		  formatContractAuditState:function(item){
		    return hlCodeConvert.contractAuditState(item)
		  },
		  formatNum: function(item) {
		    return hlNumberUtil.formatNum(item)
		  }
		},
		methods: {
			handleScroll(vertical, horizontal) {
					this.scrollSubtotalX = horizontal.process*100
			},
			payPlanDataRecombination () {
				if (!this.newData.length) {return};
				let obj = {O: []};
				let count = 4;
				if (this.intentionAmount) {
					count = 5;
				}
				let width = 140;
				let oWidth = 0;
				this.types.map(item => {
					obj[item] = []
				})
				this.newData.map(item => {
					item.total = 0;
					item.intentionAmount = '0.00';
					item.beginDate = typeof item.beginDate == 'number' ? hlDateUtil.formatUTCDate(item.beginDate, 'yyyy-MM-dd') : item.beginDate
					item.endDate = typeof item.endDate == 'number' ? hlDateUtil.formatUTCDate(item.endDate, 'yyyy-MM-dd') : item.endDate
					item.paymentDeadLineDate = typeof item.paymentDeadLineDate == 'number' ? hlDateUtil.formatUTCDate(item.paymentDeadLineDate, 'yyyy-MM-dd') : item.paymentDeadLineDate
					this.types.map(item0 => {
						item[item0] = []
					})
					item['O'] = []
				})
				this.newData.map(item => {
					item.expenseList.map(item0 => {
						if (item0.customPeriod) {
							item0.customPeriod.map(item1 => {
								item1.begin_date = hlDateUtil.formatUTCDate(item1.beginDate, 'yyyy-MM-dd')
								item1.end_date = hlDateUtil.formatUTCDate(item1.endDate, 'yyyy-MM-dd')
							})
						}
					})
				})
				//操蛋的意向金特殊处理
				if (this.intentionAmount) {
					this.newData[0].intentionAmount = -JSON.parse(JSON.stringify(Math.abs(this.intentionAmount)))
				}
				//根据expenseType分类
				this.newData.map(item => {
					item.expenseList.map(exp => {
						// 除了意向金,一次性费用全部装在一起，顺序根据types里面数组顺序执行
						if (this.types.indexOf(exp.expenseType) >= 0) {
							item[this.types[this.types.indexOf(exp.expenseType)]].push(JSON.parse(JSON.stringify(exp)))
						}
						//一次性费用单独装在一个盒子里面，根据otypes来区分是否是一次性费项
						if (this.oTypes.indexOf(exp.expenseType) >= 0) {
							item['O'].push(JSON.parse(JSON.stringify(exp)))
						}
					})
				})
				//等值赋予array
				this.newData.map(item => {
					for (let key in obj) {
						obj[key] = JSON.parse(JSON.stringify(obj[key].concat(item[key])))
					}
				})
				// 去除重复费用
				for (let key in obj) {
					obj[key] = hlArrayUtil.removeRepeat(obj[key], 'name')
				}
				//费项全部执行#处理，并且赋予索引
				for (let key in obj) {
					obj[key].map((item, index) => {
						item['expense'] = '#';
						item['expenselateFee'] = '#';
						item['customPeriod'] = [];
						item['index'] = index;
					})
				}
				// 类型相等赋予newdata
				this.newData.map(item => {
					for (let key in obj) {
						Object.keys(item).forEach(v=>{
								if (v == key) {
									item[key] = JSON.parse(JSON.stringify(item[key].concat(obj[key])))
								}
						})
					}
				})
				// 把索引给与已有费项
				this.newData.map(item => {
					for (let key in obj) {
						item[key].map(item0 => {
							Object.keys(item).forEach(v=>{
									if (v == key) {
										obj[key].map(item1 => {
											if (item0.name == item1.name) {
												item0['index'] = JSON.parse(JSON.stringify(item1['index']))
											}
										})
									}
							})
						})
					}
				})
				// 去除多余费项
				this.newData.map(item => {
					this.types.map(item0 => {
						item[item0] = hlArrayUtil.removeRepeat(item[item0], 'name')
					})
					item['O'] = hlArrayUtil.removeRepeat(item['O'], 'name')
				})
				// 金额俩位小数处理
				this.newData.map(item => {
					this.types.map(item0 => {
						item[item0].map(item1 => {
							if (!isNaN(item1.expense)) {
								item1.expense = Number(item1.expense).toFixed(2)
							}
						})
					})
					item['O'].map(item1 => {
						if (!isNaN(item1.expense)) {
							item1.expense = Number(item1.expense).toFixed(2)
						}
					})
				})
				// 根据索引排序
				this.newData.map(item => {
					this.types.map(item0 => {
						item[item0] = item[item0].sort(hlArrayUtil.compareAvg('index'))
						item[item0 + 'len'] = item[item0].length
					})
					item['O'] = item['O'].sort(hlArrayUtil.compareAvg('index'))
				})
				//操蛋的抽成金额单独处理
				this.newData.map(item => {
					item['CM'].map(item0 => {
						if (item0.expense == 0) {
							item0.expense = '实计'
						}
					})
				})

				if (this.newData[0]['O'].length) {
					this.oFlag = true;
				}
				if (!this.newData[0]['O'].length) {
					this.oFlag = false;
				}

				this.totalCalculation()
			},
			//每行金额总计
			totalCalculation () {
				this.newData.map(item => {
					item.total = 0;
					this.types.map(item0 => {
						item[item0].map(item1 => {
							if (!isNaN(item1.expense)) {
								item.total += Number(item1.expense)
							}
						})
					})
					item['O'].map(item1 => {
						if (!isNaN(item1.expense)) {
							item.total += Number(item1.expense)
						}
					})
					item.total += Number(item.intentionAmount)
				})
				this.newData.map(item => {
					this.types.map(item0 => {
						item[item0].map(item1 => {
							if (item1.expense == '实计') {
								item.total = '实计'
							}
						})
					})
				})
				//小计
				this.subtotal()
			},
			//小计
			subtotal () {
				let obj = {O: []};
				let count = 0;
				if (this.intentionAmount) {
					count = 1
				}
				this.oObj.expense = 0;
				this.types.map(item => {
					obj[item] = []
				})
				for (let key in obj) {
					obj[key] = JSON.parse(JSON.stringify(this.newData[0][key]))
					let item = key + 'len'
					obj[item] = this.newData[0][item]
				}
				for (let key in obj) {
					if (Array.isArray(obj[key])) {
						obj[key].map(item => {
							if (item.expenseType != 'CM') {
								item.expense = 0
							}
							if (item.expenseType == 'CM') {
								item.expense = '实计'
							}
						})
					}
				}
				for (let key in obj) {
					if (Array.isArray(obj[key])) {
						obj[key].map(item => {
							this.newData.map(item0 => {
								item0[key].map(item1 => {
									if (item.name == item1.name) {
										if (!isNaN(item1.expense)) {
											item.expense += Number(item1.expense)
										}
									}
								})
							})
						})
					}
				}
				obj['O'].map(item => {
					this.oObj.expense += Number(item.expense)
				})
				for (let key in obj) {
					if (this.types.indexOf(key) > -1) {
						count += obj[key].length
					}
				}
				if (obj['O'].length) {
					obj['Olen'] = JSON.parse(JSON.stringify(obj['O'].length))
					count +=1
				}
				if (count < 5) {
					this.subtotalTableWidth = (this.$refs.paySubtotalScroll.offsetWidth-140)/count
				}

				this.subtotalArr = obj;

				this.payTotal()
				// 滚动初始化
				this.rollInit()
			},
			//合计应付
			payTotal () {
				this.total = 0;
				for (let key in this.subtotalArr) {
					if (Array.isArray(this.subtotalArr[key])) {
						this.subtotalArr[key].map(item => {
							if (!isNaN(item.expense)) {
								this.total += Number(item.expense)
							}
						})
					}
				}
			},
			//滚动初始化
			rollInit () {
				const self = this;
				let disx = 0;
				function scrollFunc (e, ref){
					e=e||window.event;
					if (e&&e.preventDefault){
						if (e.deltaY > 0) {
							disx += 10
						}
						if (e.deltaY < 0) {
							disx -= 10
						}
						if (disx > 100) {disx=100}
						if (disx < 0) {disx = 0}
						self.$refs[ref].scrollTo(
							{
								x: disx + '%'
							},
							10
						);
						e.preventDefault();
						e.stopPropagation();
					}else{
					 e.returnvalue=false;
					 return false;
					}
				}

				if (this.newData.length) {
					this.$refs.paySubtotalScroll.onmouseenter = function () {
						disx = self.scrollSubtotalX;
						scrollLeft(self.$refs.paySubtotalScroll, 'scrollSubtotal')
					}

					this.$refs.paySubtotalScroll.onmouseleave = function () {
						self.$refs.paySubtotalScroll.onmousewheel = null;
					};
				}

				function scrollLeft (el, ref) {
					function addEventListFn(e) {scrollFunc(e, ref)}
					el.onmousewheel = addEventListFn
				}
			},

			//只显示变更信息
			cutChangeFlow () {
				this.cutChangeFlowFlag = !this.cutChangeFlowFlag;
				if (this.cutChangeFlowFlag) {
					this.publicLogsTypes = ['change', 'delete']
					this.publicGroup = ['Y']
					this.publicFlag = ['Y']
				}
				if (!this.cutChangeFlowFlag) {
					this.publicLogsTypes = ['text', 'value', 'change', 'delete']
					this.publicGroup = ['Y', 'N']
					this.publicFlag = ['Y', 'N']
				}
			},

			handleTabClick (ops) {
				this.selectTabData = ops.name;
			},
			versionevent () {
				this.versionDisplay = !this.versionDisplay;
				if (this.versionDisplay) {
					hlhttp.get({
						url: 'contract_history/_contrast/alter_id',
						data: {alter_id: this.params.businessId},
						success: (data) => {
							let type = ['add', 'change', 'delete']
							data.groupLogs.map(item => {
								item.group = 'N'
								item.logRecords.map(item1 => {
									item1.rowData.map(item2 => {
										if (type.indexOf(item2.logType) >= 0) {
											item.group = 'Y'
										}
									})
								})
							})
							this.groupLogs = data.groupLogs;
						}
					})
				}
			},
			//获取详情
			getData:function(){
			  var self = this;
			  hlhttp.get({
			    url: 'contract_history',
			    data:{'alter_id':self.params.businessId},
			    success: function (data) {
						self.contractBdate = hlDateUtil.formatUTCDate(data.beginDate, 'yyyy-MM-dd')
            self.contractEdate = hlDateUtil.formatUTCDate(data.endDate, 'yyyy-MM-dd')

						if(data.alterInfoVO.agreementFlag == 'Y'){
							let names = data.alterInfoVO.agreementAttachmentNames.split(',')
							let urls = data.alterInfoVO.agreementAttachmentUrls.split(',')
							names.map((item,index) =>{
								self.alertFile.push({
									name:item,
									url:urls[index]
								})
							})
						}
						self.tmpData = data.pageCustomizeComponentBizContentList ? data.pageCustomizeComponentBizContentList : []
						if(data.customConfigProperty){
              data.customConfigProperty = JSON.parse(data.customConfigProperty)
            }
						if (data.alterInfoVO.alterType != 'YB') {
							self.tabData = [
								{name: '合同变更信息', disabled: true, privilege: null},
								{name: '账单变更信息', disabled: true, privilege: null},
								{name: '流程信息', disabled: true, privilege: null},
							]
						}
						self.billChangeInfo(data.alterInfoVO.alterId)
						self.dealWithbillData(data.alterInfoVO.alterId)
						self.billParams = {history_contract_id: data.id}
						// 单元
						var buildingData = self.unitData(data.units)
						self.totalArea = data.rentAcreage
						self.building = buildingData.building
						// 车位
						self.unit = [];
						self.st = [];
						self.wp = [];
						var stTotalNum = 0;
						var wpTotalNum = 0;
						data.units.map(function (item) {
						  if (item.positions && item.unitType === 'ST') {
						    stTotalNum = stTotalNum + item.positions.length;
						    item['num'] = item.positions.length;
						    self.st.push(item)
						  }
						  if (item.positions && item.unitType === 'WP') {
						    wpTotalNum = wpTotalNum + item.positions.length;
						    item['num'] = item.positions.length;
						    self.wp.push(item)
							}
							if (item.unitType === 'BU') {
                self.unit.push(item)
              }
						})
						self.stTotalNum = stTotalNum;
						self.wpTotalNum = wpTotalNum;
						if (!data.commissionRules) {
						  data.commissionRules = []
						}
						// 租金数据
						self.rent = [];
						if (data.rentIncreseDate && data.rentIncreseDate.split(',').length > 1) {
						  for (var i = 1; i < data.rentIncreseDate.split(',').length; i++) {
						    self.rent.push({
						      beginDate: data.rentIncreseDate.split(',')[i],
						      percent: data.rentIncresePercent.split(',')[i] ? data.rentIncresePercent.split(',')[i] : '',
						      price: data.rentIncresePrice ? data.rentIncresePrice.split(',')[i] : '',
						      dayPrice: data.rentIncreseDay ? data.rentIncreseDay.split(',')[i] : '',
						      monthPrice: data.rentIncreseMonth ? data.rentIncreseMonth.split(',')[i] : ''
						    })
						  }
						}
						// 折扣月租金
            if (data.rentIncreseDiscountDay) {
              let arr1 = data.rentIncreseDiscountRate.split(',')
              let arr2 = data.rentIncreseDiscountDay.split(',')
              let arr3 = data.rentIncreseDiscountMonth.split(',')
              self.rent.map((item, index) => {
                item.discount = arr1[index + 1]
                item.discountD = arr2[index + 1]
                item.discountM = arr3[index + 1]
              })
            }
						// 合同免租期
						self.freeDate = [];
						if (data.freeDates) {
							self.freeDate = data.freeDates
						}
						// 费用数据
						self.pExpense = [];
						self.oExpense = [];
						self.tExpense = [];
						if (data.expenses) {
						  for (var j = 0; j < data.expenses.length; j++) {
						    if (data.expenses[j].expenseType == 'P') {
						      self.pExpense.push(data.expenses[j])
						    }
						    if (data.expenses[j].expenseType == 'O') {
						      self.oExpense.push(data.expenses[j])
						    }
						    if (data.expenses[j].expenseType == 'T') {
						      self.tExpense.push(data.expenses[j])
						    }
						  }
						}

						// 合同文件数据
						if (data.attachmentNames) {
						  for (var k = 0; k < data.attachmentNames.length; k++) {
						    var fileObj = {
						      name: data.attachmentNames[k],
						      url: data.attachmentUrls[k]
						    }
						    self.contractFile.push(fileObj)
						  }
						}

			      self.data = data;
						self.contract = data;
			    }
			  })
			},
			//工位车位处理
			unitData: function (unitsData) {
			  // 去除含有工位车位的单元
			  var units = [];
			  unitsData.map(function (_item) {
			    if (_item.positions.length === 0) {
			      units.push(_item)
			    }
			  })
			  if (units.length === 0) {
			    return {
			      building: [],
			      totalArea: 0
			    }
			  }
			  // 合并单元项
			  var unit = [];
			  var totalArea = 0;
			  for (var i = 0; i < units.length; i++) {
			    unit.push({
			      buildingName: units[i].buildingName,
			      floorNum: units[i].floorNum,
			      floorName: units[i].floorName,
			      unit: [],
			      unitId: []
			    })
			  }
			  var unitArr = unit.removeRepeatBuildingAndFLoor()
			  for (var z = 0; z < unitArr.length; z++) {
			    for (var m = 0; m < units.length; m++) {
			      if (units[m].buildingName == unitArr[z].buildingName && units[m].floorNum == unitArr[z].floorNum) {
			        unitArr[z].unit.push(units[m].unitName + '(' + hlNumberUtil.formatNum(units[m].unitAcreage) + 'm²)')
			        unitArr[z].unitId.push(units[m].unitId)
			        totalArea = totalArea + Number(units[m].unitAcreage)
			      }
			    }
			  }
			  // 合并楼层项
			  var building = [];
			  for (var j = 0; j < unitArr.length; j++) {
			    building.push({
			      buildingName: unitArr[j].buildingName,
			      floor: []
			    })
			  }
			  var buildingArr = hlArrayUtil.removeRepeat(building, 'buildingName')
			  for (var k = 0; k < buildingArr.length; k++) {
			    for (var n = 0; n < unitArr.length; n++) {
			      if (unitArr[n].buildingName == buildingArr[k].buildingName) {
			        buildingArr[k].floor.push({
			          'floorNum': unitArr[n].floorNum,
			          'floorName': unitArr[n].floorName,
			          'unit': unitArr[n].unit,
			          'unitId': unitArr[n].unitId
			        })
			      }
			    }
			  }
			  return {
			    building: buildingArr,
			    totalArea: totalArea
			  }
			},
			// 获取单元详情
			getUnitDetails: function (unitId) {
			  var self = this;
			  self.unitId = unitId;
			  self.unitDetailsFlag = true;
			},
			closeUnitPop: function (state) {
			  this.unitId = null;
			  this.unitDetailsFlag = false;
			},

			// 付款计划数据处理
			dealWithbillData:function (id) {
			  var self = this;
			  hlhttp.get({
			    url: 'contract_alter/bill_plans',
			    data: {contract_alter_id: id},
			    success: function(data) {
						self.payData = data.billPlan;
						self.oldPayData = data.addedBillPlan;
						self.newData = data.billPlan.concat(data.addedBillPlan)
						
						setTimeout(() => {
							self.payPlanDataRecombination()
							console.log(self.$refs.payData)
							let arr = self.$refs.payData.subtotalArr.R || []
							let gdzj = ''
							arr.map(item =>{
								if(item.name == "固定租金"){
									gdzj = item.expense
								}
							})
							self.isSatisfyMinPrice(gdzj)
						}, 100)
			    }
			  })
			},
			// 获取破底价配置
			getBreakPrice(){
				hlhttp.get({
					url: 'configure/dict',
					data: {
						'module_code': 'CIWU',
						'config_name': 'CW_BREAK_PRICE_REMINDER_TYPE_CONFIG'
					},
					success: res => {
						// CONTRASTPRICE 与预签约单价比较
						// CONTRASTRENT  与有效租金比较
						this.breakPriceFlag = res[0].dictValue == 'CONTRASTRENT'? 'CR':'CP'
					}
				})
			},
			// 判断价格是否符合底价策略
      isSatisfyMinPrice:function(num){
        var self = this;
        // 所选合同类型  WP 工位   UN 单元
        var type = self.contract.contractType === 'WR' ? 'WP' : 'UN'
        // 所选单元或者工位id  如果只选车位 则不掉用底价策略
        var getUnitIds = function(){
          var res = [];
          self.unit.map(function(_item){
            res.push(_item.unitId)
          })
          res = hlArrayUtil.arrUnique(res)
          return res.join()
        }
        var getWpIds = function(){
          var res = [];
          self.wp.map(function(item){
            item.positions.map(function(_item){
              res.push(_item.positionId)
            })
          })
          res = hlArrayUtil.arrUnique(res)
          return res.join()
        }
        var ids = null;
        if(type === 'WP'){ ids = getWpIds()}
        if(type === 'UN'){ ids = getUnitIds()}
        // 日租金、月租金计算
        var acreage = self.totalArea ? self.totalArea : this.wpTotalNum;
        var rentPriceDay = self.contract.rentPriceDay / acreage;
				var rentPriceMonth = self.contract.rentPriceMonth / acreage
				
				console.log(self.unit)
				console.log(self.wp)


        if(self.unit.length !== 0 || self.wp.length !== 0){
          hlhttp.put({
            url:'check_base_price_policy',
            data:{
              rent_price_day:Number(rentPriceDay).toFixed(2),
              rent_price_month:Number(rentPriceMonth).toFixed(2),
              type:type,
              ids:ids,
              policy_type:self.breakPriceFlag || '#',
              contract_amount:num || '#',
              contract_begin_date:self.contractBdate || '#',
              contract_end_date:self.contractEdate || '#',
            },
            success:function(data){
              if (data.result === 'N') {
                if (data.rentPriceType === 'D') {
                  if (type === 'WP') {
                    self.dayRentPriceAlert = '日租金' + (self.breakPriceFlag == 'CR'?('有效租金' + data.effectiveRentDay + '元/个/天,'):'')  + '低于工位底价' + data.memo + '元/个/天'
                    self.monthRentPriceAlert = ''
                  }
                  if (type === 'UN') {
                    self.dayRentPriceAlert = '日租金' + (self.breakPriceFlag == 'CR'?('有效租金' + data.effectiveRentDay + '元/m²/天,'):'')  + '低于单元底价' + data.memo + '元/m²/天'
                    self.monthRentPriceAlert = ''
                  }
                }
                if (data.rentPriceType === 'M') {
                  if (type === 'WP') {
                    self.monthRentPriceAlert = '月租金' + (self.breakPriceFlag == 'CR'?('有效租金' + data.effectiveRentMonth + '元/个/月,'):'')  + '低于工位底价' + (Number(data.memo)).toFixed(2) + '元/个/月'
                    self.dayRentPriceAlert = ''
                  }
                  if (type === 'UN') {
                    self.monthRentPriceAlert = '月租金' + (self.breakPriceFlag == 'CR'?('有效租金' + data.effectiveRentMonth + '元/m²/月,'):'')  + '低于单元底价' + (Number(data.memo)).toFixed(2) + '元/m²/月'
                    self.dayRentPriceAlert = ''
                  }
                }
                if (data.rentPriceType === 'A') {
                  if (type === 'WP') {
                    self.dayRentPriceAlert = '日租金' + (self.breakPriceFlag == 'CR'?('有效租金' + data.effectiveRentDay + '元/个/天,'):'')  + '低于工位底价' + data.memo.split(',')[0] + '元/个/天'
                    self.monthRentPriceAlert = '月租金' + (self.breakPriceFlag == 'CR'?('有效租金' + data.effectiveRentMonth + '元/个/月,'):'')  + '低于工位底价' + Number(data.memo.split(',')[1] || '0').toFixed(2) + '元/个/月'
                  }
                  if (type === 'UN') {
                    self.dayRentPriceAlert = '日租金' + (self.breakPriceFlag == 'CR'?('有效租金' + data.effectiveRentDay + '元/m²/天,'):'')  + '低于单元底价' + data.memo.split(',')[0] + '元/m²/天)'
                    self.monthRentPriceAlert = '月租金' + (self.breakPriceFlag == 'CR'?('有效租金' + data.effectiveRentMonth + '元/m²/月,'):'')  + '低于单元底价' + Number(data.memo.split(',')[1] || '0').toFixed(2) + '元/m²/月'
                  }
                }
              }
              if (data.result === 'Y') {
                self.dayRentPriceAlert = ''
                self.monthRentPriceAlert = ''
              }
			  self.effectiveRD = data.effectiveRentDay
			  self.effectiveRM = data.effectiveRentMonth
            }
          })
        }
      },
			// 导出账单
			exportBill:function () {
			  var self = this;
			  $.ajax({
			    url: exclUrl+'resource/bill_excel',
			    type: 'get',
			    headers: {token: Cookies.get("token")},
			    data: {contract_id: self.contractId},
			    success: function (res) {
			      var a = document.createElement('a');
			      a.href = res.excel_url;
			      $('body').append($(a))
			      a.click();
			      setTimeout(function() {
			        $(a).remove()
			      }, 100);
			    }
			  })
			},

			// 通过审核
			passAudit:function () {
			  var self = this;
			  hllayer.prompt({
			    title:'审核通过',   // 标题  默认为空
			    placeholder:'审核通过原因说明（非必填）',
			    leftBtn:'提交',
			    confirm:function (mes) {
			      $('.hllayer-mask, .hllayer-view').remove()
			      hlhttp.put({
			        url:'bpm/_pass',
			        data:{
			          bpm_key: 'CCT',
			          task_id:self.params.taskId,
			          bpm_id:self.params.bpmId,
			          memo:mes || '#',
								state: self.data.alterInfoVO.status
			        },
			        success:function (data) {
			          hl.toast('审核通过')
			          hllayer.close();
			          self.flowState = false
			          hlUrlUtil.goTo('todo', {stateName: 'CCT',projectIds:self.params.projectIds, ddtab:true})
			        }
			      })
			    }
			  })
			},
			// 未通过审核
			notPassAudit:function () {
			  var self = this;
			  hllayer.prompt({
			    title:'审核不通过',
			    placeholder:'审核不通过原因说明（必填）',
			    leftBtn:'提交',
			    confirm:function (mes) {
			      if(!mes){
			        hl.toast('请填写审核不通过的原因')
			        return
			      }
			      hlhttp.put({
			        url:'bpm/_reject',
			        data:{
			          task_id:self.params.taskId,
			          bpm_id:self.params.bpmId,
			          memo:mes,
								state: self.data.alterInfoVO.status
			        },
			        success:function (data) {
			          hl.toast('审核不通过')
			          hllayer.close();
			          hlUrlUtil.goTo('todo', {stateName: 'CCT',projectIds:self.params.projectIds, ddtab:true})
			        }
			      })
			    }
			  })
			},

			// 获取账单变更信息
			billChangeInfo (id) {
				hlhttp.get({
					url: 'bill/alter_info',
					data: {contract_alter_id: id},
					success: (data) => {
						if (!data.confilctSettleUpBill) {
							data.confilctSettleUpBill = {billExpense: [], totalAmountReceive: 0}
						}
						this.billChangeData = data;
						this.conflictBills = data.conflictBills
						let ex = data.conflictBills[0].expenses[0].withdrawAmount
						this.moneyCha = (ex.amountPayed*1 + ex.derateExpense*1 + ex.carryOverAmount*1 - ex.amountReceive*1).toFixed(2)
					}
				})
			},

			calculateTimeDifference:function(item1,item2){
			  return hlDateUtil.timeDifference(item1,item2)
			},
			// 获取流程详情数据
			getBpmDetailData:function () {
			  var self = this;
			  hlhttp.get({
			    url:'bpm',
			    data:{
			      bpm_key:'CCT',
			      bpm_id:self.params.bpmId
			    },
			    success:function (data) {
			      var newArr = data;
			      var bpdefId = data.bpdefId || 0
			      self.$set(self.$data, 'bpm', newArr)
			      self.getFlowNodeData(bpdefId)
			    }
			  })
			},
			// 获取流程节点数据
			getFlowNodeData:function (id) {
			  var self = this;
			  // 当所传id为0时展示最初始的业务节点图   ====>  开始 ----- 合同审核  ----- 结束
			  if(id === 0){
			    var nodeData = [{
			      name:'合同审核'
			    }]
			    self.flowNode = nodeData;

			  }
			  if(id !== 0){
			    hlhttp.get({
			      url:'bpdef_phases',
			      data:{'bpdef_id':id},
			      success:function(data){
			        self.flowNode = data
			      }
			    })
			  }

			},
			// 获取工作流程任务列表数据
			getBpmListData:function () {
			  var self = this;
			  hlhttp.get({
			    url:'bpm/tasks',
			    data:{bpm_id:self.params.bpmId},
			    success:function (data) {
			      var newArr = [];
			      for(var i = 0; i<data.length; i++){
			        if(data[i]['endTime'])newArr.push(data[i]);
			      }
			      self.$set(self.$data, 'bpmList', newArr)
			    }
			  })
			},
		},
		mounted () {
			this.getData()
			this.getBpmDetailData()
			this.getBpmListData()
			this.getBreakPrice()
		}
	})
} ())
